import 'package:country_code_picker/country_code_picker.dart';
import 'package:efood_multivendor/controller/transaction_controller.dart';
import 'package:efood_multivendor/controller/user_controller.dart';
import 'package:efood_multivendor/data/model/body/send_points_body.dart';
import 'package:efood_multivendor/util/functions.dart';
import 'package:efood_multivendor/view/base/custom_button.dart';
import 'package:efood_multivendor/view/base/custom_snackbar.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:permission_handler/permission_handler.dart';

import '../../../controller/auth_controller.dart';
import '../../../controller/splash_controller.dart';
import '../../../util/dimensions.dart';
import '../../../util/styles.dart';
import '../../base/custom_text_field.dart';

class WalletPointBottomSheet extends StatefulWidget {
  @override
  _WalletPointBottomSheetState createState() => _WalletPointBottomSheetState();
}

class _WalletPointBottomSheetState extends State<WalletPointBottomSheet> {
  final TextEditingController _phoneController = TextEditingController();
  final TextEditingController _amountController = TextEditingController();
  final FocusNode _phoneFocus = FocusNode();
  final FocusNode _amountFocus = FocusNode();
  String? _countryDialCode =
      Get.find<AuthController>().getUserCountryCode().isNotEmpty
          ? Get.find<AuthController>().getUserCountryCode()
          : CountryCode.fromCountryCode(
                  Get.find<SplashController>().configModel?.country ?? 'ET')
              .dialCode;

  Future<void> _importContact() async {
    PermissionStatus permissionStatus = await Permission.contacts.request();
    // if (permissionStatus.isGranted) {
    //   Contact contact = await ContactsService.openDeviceContactPicker();
    //   if (contact != null &&
    //       contact.phones != null &&
    //       contact.phones.isNotEmpty) {
    //     setState(() {
    //       _phoneController.text = UtilFunctions.removeCountryCode(
    //           contact.phones.first.value?.replaceAll(' ', '') ?? '');
    //     });
    //   }
    // } else if (permissionStatus.isDenied) {
    //   showDialog(
    //     context: context,
    //     builder: (context) => AlertDialog(
    //       title: Text("Permission Denied"),
    //       content:
    //           Text("Contacts permission is required to import a phone number."),
    //       actions: [
    //         TextButton(
    //           onPressed: () => Navigator.of(context).pop(),
    //           child: Text("OK"),
    //         ),
    //       ],
    //     ),
    //   );
    // }
  }

  void _sendPoints() {
    String phoneNumber = _phoneController.text;
    String amount = _amountController.text;

    String currentUserNumberWoCountryCode = UtilFunctions.removeCountryCode(
        Get.find<UserController>().userInfoModel!.phone!);

    if (phoneNumber == currentUserNumberWoCountryCode) {
      showCustomSnackBar("You can't send to your own account");
    } else if (phoneNumber.isNotEmpty && amount.isNotEmpty) {
      SendPointsBody sendPointsBody = SendPointsBody(
        phone: phoneNumber.trim(),
        amount: int.parse(amount.trim()),
        countryCode: '+251',
      );

      Get.find<TransactionController>()
          .sendPoint(sendPointsBody)
          .then((success) {
        if (success) {
          Get.back();
          showCustomSnackBar(
              "Wallet points sent to $phoneNumber for amount: $amount",
              isError: false);
          Get.find<TransactionController>().getTransactionDetails(1);
          Get.find<UserController>().getUserInfo();
        }
      });
    } else {
      showCustomSnackBar("Please enter a valid phone number and amount");
    }
  }

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: EdgeInsets.only(
        bottom: MediaQuery.of(context).viewInsets.bottom,
      ),
      child: SingleChildScrollView(
        child: Padding(
          padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 20.0),
          child: Column(
            children: [
              Text(
                "Send Wallet Points",
                style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
              ),
              SizedBox(height: 20),
              Container(
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(Dimensions.RADIUS_SMALL),
                  color: Theme.of(context).cardColor,
                  boxShadow: [
                    BoxShadow(
                        color: Colors.grey[Get.isDarkMode ? 800 : 200]!,
                        spreadRadius: 1,
                        blurRadius: 5)
                  ],
                ),
                child: Column(children: [
                  Row(children: [
                    SizedBox(
                      width: 10,
                    ),
                    Center(
                      child: Text(
                        _countryDialCode ?? '',
                        style: sfRegular,
                      ),
                    ),
                    Expanded(
                        flex: 10,
                        child: CustomTextField(
                          hintText: 'phone'.tr,
                          controller: _phoneController,
                          focusNode: _phoneFocus,
                          nextFocus: _amountFocus,
                          inputType: TextInputType.phone,
                          divider: false,
                          // suffixIcon: IconButton(
                          //   icon: Icon(Icons.contacts),
                          //   onPressed: _importContact,
                          // ),
                        )),
                  ]),
                ]),
              ),
              SizedBox(height: 20),
              //      TextField(
              //   controller: _phoneController,
              //   keyboardType: TextInputType.phone,
              //   decoration: InputDecoration(
              //     labelText: "Phone Number",
              //     prefixIcon: Icon(Icons.phone),
              //     suffixIcon: IconButton(
              //       icon: Icon(Icons.contacts),
              //       onPressed: _importContact,
              //     ),
              //     border: OutlineInputBorder(),
              //   ),
              // ),
              CustomTextField(
                controller: _amountController,
                nativePrefixIcon: Icons.account_balance_wallet,
                hintText: "Enter amount to send",
              ),
              SizedBox(height: 20),
              GetBuilder<TransactionController>(
                builder: (controller) {
                  return controller.isPointSendLoading
                      ? CircularProgressIndicator()
                      : CustomButton(
                          onPressed: _sendPoints,
                          buttonText: "Send Points",
                        );
                },
              ),
            ],
          ),
        ),
      ),
    );
  }
}
